/**
 * 
 */
package com.mc.thumbnailator;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

/**
 * 图片处理的Google开源Java类库 测试
 * @author w.weizhen
 *
 */
public class Thumbnailator {
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        
        test();// 测试
        
    }
    
    private static void test()
    {
//        String fromPic = "D:/hynetic/file/M站转换App和推送消息.docx";
//        String toPic = "D:/hynetic/file/微信图片_20210617175401_thumbnailator.jpg";
        
        String fromPic = "D:\\文件\\日期文件\\202106190\\wlwzxjcdp\\img\\ui-02.png";
        String toPic = "D:\\文件\\日期文件\\202106190\\wlwzxjcdp\\img\\ui-020.jpg";
        
        try {
            //按照比例进行缩小和放大
            //Thumbnails.of(fromPic).scale(0.1f).toFile(toPic);//按比例缩小
            //Thumbnails.of(fromPic).scale(2f);//按比例放大
            
            //图片尺寸不变，压缩图片文件大小outputQuality实现,参数1为最高质量
            //Thumbnails.of(fromPic).scale(1f).outputQuality(0.1f).toFile(toPic);
            
            // 图片比例不变
            //Thumbnails.of(fromPic).size(500, 300).toFile(toPic);
            
            //不保持图片比例
            //Thumbnails.of(fromPic).forceSize(500, 300).toFile(toPic);
            
            //向右旋转
            //Thumbnails.of(fromPic).rotate(90f).toFile(toPic);
            
            //加水印 位置，水印来源，透明度
            //Thumbnails.of(fromPic).watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(fromPic)), 0.5f).toFile(toPic);
            
            //裁剪
//            Thumbnails.of(fromPic)
//            .sourceRegion(Positions.CENTER, 800, 600) //位置，宽，高
//            .size(800, 600)
//            .keepAspectRatio(false)
//            .toFile(toPic);
            
            thumbnails(fromPic, toPic, 921600);
            
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 压缩图片大小至某大小
     * @param from 路径
     * @param to 路径
     * @param maxSize 文件最大大小
     * @return
     * @throws IOException 
     */
    private static void thumbnails(String from, String to, long maxSize) throws IOException
    {
        if(StringUtils.isBlank(from)||!new File(from).isFile())
        {
            return;
        }
        long size = FileUtils.sizeOf(new File(from));
        System.out.println(FileUtils.byteCountToDisplaySize(size));
        if (size >= maxSize) 
        {
            Thumbnails.of(from).scale(0.9f).toFile(to);//按比例缩小
            thumbnails(to, to, maxSize);
        }
        else
        {
            Thumbnails.of(from).scale(1f).toFile(to);
            if(FileUtils.sizeOf(new File(to)) >= maxSize)
            {
                thumbnails(to, to, maxSize);
            }
        }
    }
}